package likou.tanxin;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/08 07:58
 */
public class _327 {

    static int lower, upper;
    static int count;
    public static int countRangeSum(int[] nums, int lower, int upper) {

        _327.lower = lower;
        _327.upper = upper;
        _327.count = 0;

        int n = nums.length;

        long[] preSum = new long[n + 1];
        preSum[0] = 0;
        for (int i = 0; i < n; i++) {
            preSum[i + 1] = preSum[i] + nums[i];
        }

        sort(preSum, new long[n + 1], 0, n);

        return count;
    }

    private static void sort(long[] preSum, long[] aux, int lo, int hi) {
        if (lo >= hi) return;
        int mid = lo + (hi - lo) / 2;
        sort(preSum, aux, lo, mid);
        sort(preSum, aux, mid + 1, hi);
        merge(preSum, aux, lo, mid, hi);
    }

    private static void merge(long[] preSum, long[] aux, int lo, int mid, int hi) {

        for (int i = lo; i <= hi; i++) {
            aux[i] = preSum[i];
        }

        int i = lo, j = mid + 1;
        int lowerIdx = mid + 1, upperIdx = mid + 1;

        for (int k = lo; k <= hi; k++) {

            while (lowerIdx <= hi && aux[lowerIdx] - aux[i] < lower) {
                lowerIdx++;
            }
            while (upperIdx <= hi && aux[upperIdx] - aux[i] <= upper) {
                upperIdx++;
            }

            if (i > mid) {
                preSum[k] = aux[j++];
            } else if (j > hi) {
                preSum[k] = aux[i++];
                count += upperIdx - lowerIdx;
            } else if (aux[i] > aux[j]) {
                preSum[k] = aux[j++];
            } else {
                preSum[k] = aux[i++];
                count += upperIdx - lowerIdx;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(countRangeSum(new int[]{-2,5,-1},-2,2));
    }

}
